package weekthree;

public class ConstructBinaryTreeFromInorderAndPostOrder_106 {

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return build(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }

    private TreeNode build(int[] inorder, int l1, int r1, int[] postorder, int l2, int r2) {
        if (l1 > r1) return null;
        TreeNode root = new TreeNode(postorder[r2]);
        int mid = l1;
        while (inorder[mid] != postorder[r2]) {
            mid++;
        }
        int leftSize = mid - l1;
        int rightSize = r1 - mid;

        root.left = build(inorder, l1, mid - 1, postorder, l2, l2 + leftSize - 1);
        root.right = build(inorder, mid + 1, r1, postorder, r2 - rightSize, r2 - 1);
        return root;
    }

    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
